package cn.liu._05_topic;

import cn.liu.ConnectionUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

//消息发送者（生产者）
public class Send {
    //交换机名字
    public static final String NAME_EXCHANGE_TOPIC_1010 = "name_exchange_topic_1010";

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            //1.创建链接对象
            connection = ConnectionUtil.getConnection();
            //2.创建通道
            channel = connection.createChannel();
            //3.声明交换机 :TOPIC
            channel.exchangeDeclare(NAME_EXCHANGE_TOPIC_1010, BuiltinExchangeType.TOPIC,true);//true:持久化
            //4.准备消息
            String message = "This is a  message of TOPIC";

            //5.发送消息
            /**
             * 消息发布方法
             * param1：Exchange的名称，如果没有指定，则使用Default Exchange
             * param2:routingKey,消息的路由Key，是用于Exchange（交换机）将消息转发到指定的消息队列
             * param3:消息包含的属性
             * param4：消息体
             */
            channel.basicPublish(NAME_EXCHANGE_TOPIC_1010, "item.insert", null, message.getBytes());
            System.out.println("消息发送完毕：" + message);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //5.释放链接
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
